<template>
  <div class="h-full">
    <NCard title="数据模型管理" :bordered="false" class="h-full rounded-8px shadow-sm">
      <div class="h-full flex-col">
        <!-- 操作按钮 -->
        <NSpace class="pb-12px" justify="space-between">
          <NSpace>
            <NButton type="primary" @click="handleAdd">
              <template #icon>
                <icon-ic-round-plus class="text-icon" />
              </template>
              {{ $t('common.add') }}
            </NButton>
            <NButton type="error" :disabled="!selectedRowKeys.length" @click="handleBatchDelete">
              <template #icon>
                <icon-ic-round-delete class="text-icon" />
              </template>
              {{ $t('common.delete') }}
            </NButton>
          </NSpace>
          <NSpace>
            <NButton @click="handleRefresh">
              <template #icon>
                <icon-mdi-refresh class="text-icon" />
              </template>
              {{ $t('common.refresh') }}
            </NButton>
          </NSpace>
        </NSpace>

        <!-- 数据表格 -->
        <NDataTable :columns="columns" :data="dataSource" :loading="loading" :pagination="pagination"
          :row-key="(row: DataModel) => row.id" :scroll-x="1400" class="sm:h-full" flex-height remote
          @update:checked-row-keys="handleCheck" />
      </div>
    </NCard>

    <!-- 新增/编辑抽屉 -->
    <DataModelOperateDrawer v-model:visible="drawerVisible" :operate-type="operateType" :row-data="editingData"
      @submitted="getDataSource" />

    <!-- 版本历史抽屉 -->
    <VersionHistoryDrawer v-model:visible="versionVisible" :model-id="currentModelId" />
  </div>
</template>

<script setup lang="tsx">
import { reactive, ref } from 'vue';
import type { DataTableColumns, PaginationProps } from 'naive-ui';
import { NButton, NSpace, NSwitch, NTag } from 'naive-ui';
import { useBoolean, useLoading } from '@sa/hooks';
import { $t } from '@/locales';
import {
  deleteDataModel,
  getDataModelList,
  syncToDoris,
  updateDataModelStatus,
  type DataModel
} from '@/service/api/dataplatform/datamodel';
import DataModelOperateDrawer from './modules/data-model-operate-drawer.vue';
import VersionHistoryDrawer from './modules/version-history-drawer.vue';

const { loading, startLoading, endLoading } = useLoading(false);
const { bool: drawerVisible, setTrue: openDrawer } = useBoolean();
const { bool: versionVisible, setTrue: openVersionDrawer } = useBoolean();

const dataSource = ref<DataModel[]>([]);
const selectedRowKeys = ref<number[]>([]);
const operateType = ref<'add' | 'edit'>('add');
const editingData = ref<DataModel | null>(null);
const currentModelId = ref<number>();

const pagination: PaginationProps = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 15, 20, 25, 30],
  onChange: (page: number) => {
    pagination.page = page;
    getDataSource();
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.page = 1;
    getDataSource();
  }
});

const columns: DataTableColumns<DataModel> = [
  { type: 'selection', align: 'center', width: 48 },
  { key: 'name', title: () => $t('dataplatform.datamodel.name'), align: 'left', minWidth: 150, ellipsis: { tooltip: true } },
  { key: 'tableName', title: () => $t('dataplatform.datamodel.tableName'), align: 'left', minWidth: 150, ellipsis: { tooltip: true } },
  {
    key: 'tableType',
    title: () => $t('dataplatform.datamodel.tableType'),
    align: 'center',
    width: 120,
    render: row => {
      const typeMap = {
        DUPLICATE: { type: 'default', label: 'DUPLICATE' },
        AGGREGATE: { type: 'warning', label: 'AGGREGATE' },
        UNIQUE: { type: 'success', label: 'UNIQUE' }
      };
      const config = typeMap[row.tableType as keyof typeof typeMap] || typeMap.DUPLICATE;
      return <NTag type={config.type as any}>{config.label}</NTag>;
    }
  },
  { key: 'version', title: () => $t('dataplatform.datamodel.version'), align: 'center', width: 80 },
  {
    key: 'syncStatus',
    title: () => $t('dataplatform.datamodel.syncStatus'),
    align: 'center',
    width: 100,
    render: row => {
      const statusMap = {
        0: { type: 'default', label: $t('dataplatform.datamodel.notSynced') },
        1: { type: 'success', label: $t('dataplatform.datamodel.synced') },
        2: { type: 'error', label: $t('dataplatform.datamodel.syncFailed') }
      };
      const config = statusMap[row.syncStatus as keyof typeof statusMap] || statusMap[0];
      return <NTag type={config.type as any}>{config.label}</NTag>;
    }
  },
  {
    key: 'status',
    title: () => $t('common.status'),
    align: 'center',
    width: 80,
    render: row => {
      return (
        <NSwitch
          value={row.status === 1}
          onUpdateValue={(value: boolean) => handleStatusChange(row, value ? 1 : 0)}
        />
      );
    }
  },
  { key: 'createTime', title: () => $t('common.createTime'), align: 'center', width: 160 },
  {
    key: 'actions',
    title: () => $t('common.action'),
    align: 'center',
    width: 280,
    fixed: 'right',
    render: row => {
      return (
        <NSpace justify="center">
          <NButton size="small" onClick={() => handleEdit(row)}>
            {$t('common.edit')}
          </NButton>
          <NButton size="small" type="primary" onClick={() => handleSync(row)}>
            {$t('dataplatform.datamodel.sync')}
          </NButton>
          <NButton size="small" onClick={() => handleVersionHistory(row)}>
            {$t('dataplatform.datamodel.versions')}
          </NButton>
          <NButton size="small" type="error" onClick={() => handleDelete(row.id!)}>
            {$t('common.delete')}
          </NButton>
        </NSpace>
      );
    }
  }
];

async function getDataSource() {
  startLoading();
  const { data, error } = await getDataModelList({
    pageNum: pagination.page,
    pageSize: pagination.pageSize
  });
  if (!error) {
    dataSource.value = data.rows;
    pagination.itemCount = data.total;
  }
  endLoading();
}

function handleAdd() {
  operateType.value = 'add';
  editingData.value = null;
  openDrawer();
}

function handleEdit(row: DataModel) {
  operateType.value = 'edit';
  editingData.value = { ...row };
  openDrawer();
}

function handleCheck(keys: number[]) {
  selectedRowKeys.value = keys;
}

function handleBatchDelete() {
  window.$dialog?.warning({
    title: $t('common.warning'),
    content: $t('common.confirmDelete'),
    positiveText: $t('common.confirm'),
    negativeText: $t('common.cancel'),
    onPositiveClick: async () => {
      const { error } = await deleteDataModel(selectedRowKeys.value);
      if (!error) {
        window.$message?.success($t('common.deleteSuccess'));
        selectedRowKeys.value = [];
        getDataSource();
      }
    }
  });
}

function handleDelete(id: number) {
  window.$dialog?.warning({
    title: $t('common.warning'),
    content: $t('common.confirmDelete'),
    positiveText: $t('common.confirm'),
    negativeText: $t('common.cancel'),
    onPositiveClick: async () => {
      const { error } = await deleteDataModel([id]);
      if (!error) {
        window.$message?.success($t('common.deleteSuccess'));
        getDataSource();
      }
    }
  });
}

async function handleStatusChange(row: DataModel, status: number) {
  const { error } = await updateDataModelStatus(row.id!, status);
  if (!error) {
    window.$message?.success($t('common.operationSuccess'));
    getDataSource();
  }
}

async function handleSync(row: DataModel) {
  window.$dialog?.warning({
    title: $t('common.warning'),
    content: $t('dataplatform.datamodel.confirmSync'),
    positiveText: $t('common.confirm'),
    negativeText: $t('common.cancel'),
    onPositiveClick: async () => {
      const { error } = await syncToDoris(row.id!);
      if (!error) {
        window.$message?.success($t('dataplatform.datamodel.syncSuccess'));
        getDataSource();
      }
    }
  });
}

function handleVersionHistory(row: DataModel) {
  currentModelId.value = row.id;
  openVersionDrawer();
}

function handleRefresh() {
  getDataSource();
}

// 初始化
getDataSource();
</script>

<style scoped lang="scss"></style>
